package com.cheyunkeji.er.activity.evaluate;

import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.adapter.evaluate.BindCarOwnerArchiveAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.CustomerArchiveInfo;
import com.cheyunkeji.er.bean.event.RefreshUIEvent;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.utils.ToastUtil;
import com.cheyunkeji.er.view.MyRadioGroup;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

public class AddClientActivity extends BaseActivity {

    private static final String TAG = AddClientActivity.class.getSimpleName();
    //   是否编辑用户数据（如果数据从用户列表传递过来，则可以对原数据进行编辑，如果是新添加用户，则直接添加新用户）
    private static boolean IS_EDIT_CUSTOMER_INFO = false;
    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.et_carowner_name)
    EditText etCarownerName;
    @BindView(R.id.et_carowner_telenum)
    EditText etCarownerTelenum;
    @BindView(R.id.rb_personal)
    RadioButton rbPersonal;
    @BindView(R.id.rb_company)
    RadioButton rbCompany;
    @BindView(R.id.rg_client_kind)
    LinearLayout rgClientKind;
    @BindView(R.id.rb_male)
    RadioButton rbMale;
    @BindView(R.id.rb_female)
    RadioButton rbFemale;
    @BindView(R.id.rg_client_gender)
    RadioGroup rgClientGender;
    @BindView(R.id.tv_client_address)
    TextView tvClientAddress;
    @BindView(R.id.et_client_address)
    EditText etClientAddress;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.ll_add_client)
    LinearLayout llAddClient;
    @BindView(R.id.activity_add_client)
    LinearLayout activityAddClient;
    @BindView(R.id.rb_xzdw)
    RadioButton rbXzdw;
    @BindView(R.id.mrg_client_cate)
    MyRadioGroup mrgClientCate;
    private ArrayList<CustomerArchiveInfo> dataList;
    private BindCarOwnerArchiveAdapter adapter;
    private CustomerArchiveInfo archiveInfo;

    @Override
    protected void init() {
        setContentView(R.layout.er_activity_add_client);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {

        vTopbar.setTitle("添加客户");
        vTopbar.setLeftBack();

        if (!TextUtils.isEmpty(getIntent().getStringExtra("KEY_WORD"))) {
            etCarownerName.setText(getIntent().getStringExtra("KEY_WORD"));
        }

        if (null != getIntent().getSerializableExtra("CUSTOMER_INFO")) {
            archiveInfo = (CustomerArchiveInfo) getIntent().getSerializableExtra("CUSTOMER_INFO");
            displayData(archiveInfo);
            IS_EDIT_CUSTOMER_INFO = true;

        } else {

            IS_EDIT_CUSTOMER_INFO = false;
            String tempText = getIntent().getStringExtra("name");
            if (!TextUtils.isEmpty(tempText)) {
                etCarownerName.setText(tempText);
                CharSequence text = etCarownerName.getText();
                if (text instanceof Spannable) {
                    Spannable spanText = (Spannable) text;
                    Selection.setSelection(spanText, text.length());
                }
            }

        }

        tvSave.setOnClickListener(this);

    }


    private void displayData(CustomerArchiveInfo archiveInfo) {

        vTopbar.setTitle("车主档案详情");
        etCarownerName.setText(archiveInfo.getRealname());
        etCarownerTelenum.setText(archiveInfo.getPhone());
        etClientAddress.setText(archiveInfo.getAddress());

        rgClientGender.check(archiveInfo.getSex().equals("1") ? R.id.rb_male : R.id.rb_female);
        mrgClientCate.check(archiveInfo.getCategory().equals("1") ? R.id.rb_personal : archiveInfo.getCategory().equals("2") ? R.id.rb_company : R.id.rb_xzdw);

    }

    @Override
    protected void initData() {


    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.vRight:
                ToastUtil.showToast("保存");
                break;
            case R.id.tv_save:
                if (checkInputValid()) {
                    if (!IS_EDIT_CUSTOMER_INFO) {
                        insertCustomerInfo(etCarownerName.getText().toString(), etCarownerTelenum.getText().toString(), etClientAddress.getText().toString(),
                                mrgClientCate.getCheckedRadioButtonId() == R.id.rb_personal ? 1 : mrgClientCate.getCheckedRadioButtonId() == R.id.rb_company ? 2 : 3, rgClientGender.getCheckedRadioButtonId() == R.id.rb_male ? 1 : 2);
                    } else {
                        updateCustomerInfo(archiveInfo.getCid(), etCarownerName.getText().toString(), etCarownerTelenum.getText().toString(), etClientAddress.getText().toString(),
                                mrgClientCate.getCheckedRadioButtonId() == R.id.rb_personal ? 1 : mrgClientCate.getCheckedRadioButtonId() == R.id.rb_company ? 2 : 3, rgClientGender.getCheckedRadioButtonId() == R.id.rb_male ? 1 : 2);
                    }
                }
                break;
            default:
                break;
        }
    }


    private void insertCustomerInfo(String realName, String phoneNumber, String address, int clientKind, int gender) {

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("realname", realName);
        params.put("phone", phoneNumber);
        params.put("address", address);
        params.put("sex", String.valueOf(gender));
        params.put("category", String.valueOf(clientKind));

        ApiClient.postForm(HttpConstants.ADD_CUSTOMER_ARCHIVE, params, new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

                // 网络异常
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {
                try {

                    JSONObject obj = new JSONObject(response);
                    if (obj.optInt("code") == 1) {
                        SToast.show("添加成功", Gravity.CENTER);
                        MyApplication.getInstance().removeActivity(AddClientActivity.class);
                        LiveEventBus.get().with("refresh_car_ownerlist").postValue("");
                        finish();
                    } else {
                        SToast.show("添加失败", Gravity.CENTER);
                        SToast.show(obj.optString("msg"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }

        });

    }


    /**
     * 修改车主信息
     *
     * @param realName
     * @param phoneNumber
     * @param address
     * @param clientKind
     * @param gender
     */
    private void updateCustomerInfo(String cid, String realName, String phoneNumber, String address, int clientKind, int gender) {
        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("cid", archiveInfo.getCid());
        params.put("realname", realName);
        params.put("phone", phoneNumber);
        params.put("address", address);
        params.put("sex", String.valueOf(gender));
        params.put("category", String.valueOf(clientKind));
        ApiClient.postForm(HttpConstants.UPDATE_CUSTOMER_ARCHIVE_INFO, params, new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                // 网络异常
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject obj = new JSONObject(response);
                    if (obj.optInt("code") == 1) {
                        SToast.show("修改成功");
                        MyApplication.getInstance().removeActivity(AddClientActivity.class);
                        finish();
                    } else {
                        SToast.show(obj.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }
        });

    }


    /**
     * 检查输入框合法性
     *
     * @return
     */
    private boolean checkInputValid() {

        if (TextUtils.isEmpty(etCarownerName.getText().toString())) {
            SToast.show("请输入车主姓名");
            return false;
        }

        if (TextUtils.isEmpty(etCarownerTelenum.getText().toString())) {
            SToast.show("请输入车主电话");
            return false;
        }

        if (TextUtils.isEmpty(etClientAddress.getText().toString())) {
            SToast.show("请输入客户详细地址");
            return false;
        }

        return true;

    }

}
